package io.yx

import java.net.ServerSocket
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import kotlin.system.exitProcess

fun main(args: Array<String>) {

    val javaVersion = System.getProperty("java.specification.version")

    if (javaVersion.toFloat() < 21) {
        println("当前java版本:${javaVersion}不支持.本程序使用虚拟线程,需要最低的java版本为21")
        exitProcess(1)
    }

    if (args.size != 1) {
        println("请输入端口号\n例如:java -jar socketServer.jar 9000")
        exitProcess(1)
    }

    val portArg = args[0]
    if (portArg.toIntOrNull() == null || portArg.toInt() < 0 || portArg.toInt() > 65535) {
        println("请输入正确的端口号0-65535")
    }


    val port = portArg.toInt()

    val socketServer = ServerSocket(port)

    println("服务已启动成功,监听端口:$port")

    while (true) {
        val socket = socketServer.accept()

        Thread.ofVirtual().start {
            val remoteSocketAddress = socket.inetAddress.hostAddress
            println("$remoteSocketAddress 已建立链接")
            socket.use { s ->
                s.getInputStream().bufferedReader().use { bufferedReader ->
                    val nowTimeStr = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now())
                    // 获取到输出流
                    val bufferedWriter = s.getOutputStream().bufferedWriter(Charsets.UTF_8)
                    val line = bufferedReader.readLine()
                    bufferedWriter.write("$nowTimeStr 收到来自你的消息:$line")
                    bufferedWriter.newLine()
                    bufferedWriter.flush()
//                    var line: String?
//                    while (bufferedReader.readLine().also { l -> line = l } != "exit") {
//                        println("$remoteSocketAddress:$line")
//
//                        if (line?.isNotEmpty() == true) {
//                            bufferedWriter.write("$nowTimeStr 收到来自你的消息:$line")
//                            bufferedWriter.newLine()
//                            bufferedWriter.flush()
//                        }
//                    }
                }
            }
        }
    }
}


